using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class CardView : CardViewBase, IBagItemView
{
    [SerializeField] private GameObject rootGO;

    [Header("材质设置")]
    [SerializeField] private SpriteRenderer backgroundOutline;
    [SerializeField] private Material defaultMaterial;
    [SerializeField] private Material outlineMaterial;

    private Vector3 dragStartPosition;
    private Quaternion dragStartRotation;

    private bool _isHighlighted;
    public bool IsHighlighted
    {
        get => _isHighlighted;
        set
        {
            if (_isHighlighted == value) return;
            _isHighlighted = value;
            UpdateMaterial();
        }
    }

    private void Awake()
    {
        if (backgroundOutline != null)
            backgroundOutline.material = defaultMaterial;
        IsHighlighted = false;
    }

    private void UpdateMaterial()
    {
        if (backgroundOutline == null) return;
        backgroundOutline.material = _isHighlighted ? outlineMaterial : defaultMaterial;
    }

    #region IBagItemView 实现

    public EventMode EventMode { get; private set; } = EventMode.Default;
    public BagItemData BagItemData { get => card; set => Setup(value, EventMode.Default); }

    public void Setup(BagItemData data, EventMode mode = EventMode.Default)
    {
        if (data is Card c)
            Setup(c, mode);
    }

    public void Setup(Card c, EventMode mode = EventMode.Default)
    {
        EventMode = mode;
        SetupInternal(c); // 调用父类初始化逻辑（数据+UI）
        UpdateMaterial();
    }


    #endregion

    #region 鼠标事件分流

    private void OnMouseEnter()
    {
        if (EventMode == EventMode.Default)
            DefaultOnMouseEnter();
        else
            CustomOnMouseEnter();
    }

    private void OnMouseExit()
    {
        if (EventMode == EventMode.Default)
            DefaultOnMouseExit();
        else
            CustomOnMouseExit();
    }

    private void OnMouseDown()
    {
        if (EventMode == EventMode.Default)
            DefaultOnMouseDown();
        else
            CustomOnMouseDown();
    }

    private void OnMouseDrag()
    {
        if (EventMode == EventMode.Default)
            DefaultOnMouseDrag();
        else
            CustomOnMouseDrag();
    }

    private void OnMouseUp()
    {
        if (EventMode == EventMode.Default)
            DefaultOnMouseUp();
        else
            CustomOnMouseUp();
    }

    #endregion

    #region Default（原 FightScene 完整逻辑）

    private void DefaultOnMouseEnter()
    {
        if (!CardViewSystem.Instance.PlayerCanHover()) return;

        rootGO.SetActive(false);
        Vector3 pos = new Vector3(transform.position.x, -2f, 0);
        CardViewSystem.Instance.Show(card, pos);
        IsHighlighted = true;
    }

    private void DefaultOnMouseExit()
    {
        if (!CardViewSystem.Instance.PlayerCanHover()) return;

        CardViewSystem.Instance.Hide();
        rootGO.SetActive(true);
        IsHighlighted = false;
    }

    private void DefaultOnMouseDown()
    {
        if (!CardViewSystem.Instance.PlayerCanHover()) return;

        if (effectSystem != null && (effectSystem.ManualTargetEffect != null || effectSystem.IsSpecialManualTarget))
        {
            ManualTargetSystem.Instance.StartTarget(transform.position);
        }
        else
        {
            CardViewSystem.Instance.PlayerIsDragging = true;
            rootGO.SetActive(true);
            CardViewSystem.Instance.Hide();
            dragStartPosition = transform.position;
            dragStartRotation = transform.rotation;
            transform.rotation = Quaternion.Euler(0, 0, 0);
            transform.position = MouseUtil.GetMousePositionInWorldSpace(-1);
        }
    }

    private void DefaultOnMouseDrag()
    {
        if (!CardViewSystem.Instance.PlayerCanInteract()) return;

        if (effectSystem != null && (effectSystem.ManualTargetEffect != null || effectSystem.IsSpecialManualTarget)) return;

        transform.position = MouseUtil.GetMousePositionInWorldSpace(-1);
    }

    private void DefaultOnMouseUp()
    {
        if (!CardViewSystem.Instance.PlayerCanInteract()) return;

        if (effectSystem != null && effectSystem.ManualTargetEffect != null)
        {
            EnemyView target = ManualTargetSystem.Instance.EndTargeting(MouseUtil.GetMousePositionInWorldSpace(-1));
            if (target != null && ManaSystem.Instance.HasEnoughMana(ManaNumber))
            {
                PlayCardGA playCardGA = new PlayCardGA(this, target);
                ActionSystem.Instance.Perform(playCardGA);
                Debug.Log($"手动选中目标: {target.name}，执行卡牌: {card.Title} 的效果");
            }
        }
        else if (effectSystem != null && effectSystem.IsSpecialManualTarget)
        {
            EnemyView target = ManualTargetSystem.Instance.EndTargeting(MouseUtil.GetMousePositionInWorldSpace(-1));
            if (target != null && ManaSystem.Instance.HasEnoughMana(ManaNumber))
            {
                effectSystem.specialManualTarget = target;
                PlayCardGA playCardGA = new PlayCardGA(this);
                ActionSystem.Instance.Perform(playCardGA);
                Debug.Log($"特殊选中目标: {target.name}，赋值给 specialManualTarget 并执行卡牌: {card.Title} 的特殊效果");
            }
        }
        else
        {
            if (ManaSystem.Instance.HasEnoughMana(ManaNumber))
            {
                PlayCardGA playCardGA = new PlayCardGA(this);
                ActionSystem.Instance.Perform(playCardGA);
                Debug.Log($"无目标释放卡牌: {card.Title}");
            }
            else
            {
                transform.position = dragStartPosition;
                transform.rotation = dragStartRotation;
            }
            CardViewSystem.Instance.PlayerIsDragging = false;
        }
    }

    #endregion

    #region Custom（背包或自定义逻辑）

    private void CustomOnMouseEnter()
    {
        Debug.Log($"Custom 鼠标进入: {card.Title}");
    }

    private void CustomOnMouseExit()
    {
        Debug.Log($"Custom 鼠标退出: {card.Title}");
    }

    private void CustomOnMouseDown()
    {
        Debug.Log($"Custom 鼠标点击: {card.Title}");
        BagSelectedGA ga = new BagSelectedGA(this);
        ActionSystem.Instance.AddReaction(ga);
    }

    private void CustomOnMouseDrag()
    {
    }

    private void CustomOnMouseUp()
    {
    }

    #endregion
}
